package com.client.controller;

import com.Emplyment.dto.CommentDto;
import com.Emplyment.dto.InterViewDto;
import com.Emplyment.result.Result;
import com.Emplyment.vo.CommentVo;
import com.Emplyment.vo.InterViewVo;
import com.client.service.InterViewService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/interview")
@Slf4j
public class InterViewController {

    @Autowired
    private InterViewService interViewService;
    @RequestMapping("/getInterview")
    public Result<List<InterViewVo>> getInterview(@RequestParam String selectedCategory) {
        log.info("选中的职业为：{}", selectedCategory);
        List<InterViewVo> interviews = interViewService.getInterviews(selectedCategory);
        log.info("获取到的面试信息为：{}", interviews);

        if (interviews.size() == 0){
            return Result.success( new ArrayList<>());
        }

        // 使用 Stream 提取 interviewId 列表
        List<Integer> interviewIds = interviews.stream()
                .map(InterViewVo::getInterviewId) // 提取 interviewId
                .collect(Collectors.toList());    // 收集为 List

        List<CommentVo> comments = interViewService.getComments(interviewIds);
        Map<Integer, List<CommentVo>> commentMap = comments.stream()
                .collect(Collectors.groupingBy(CommentVo::getInterviewId));

        interviews.forEach(interview -> {
            Integer interviewId = interview.getInterviewId();
            List<CommentVo> comment = commentMap.get(interviewId);
            if (comment != null) {
                interview.setComments(comment);
            }
        });

        if (interviews.size() == 0){
            return Result.success( new ArrayList<>());
        }
        return Result.success(interviews);

    }

    @PostMapping("/insertInterview")
    public Result insertInterview(@RequestBody InterViewDto newPost) {
        log.info("新增面经信息：{}", newPost);
        interViewService.insertInterview(newPost);
        return Result.success();
    }

    @PostMapping("/insertComment")
    public Result insertComment(@RequestBody CommentDto newComments) {
        log.info("新增评论信息：{}", newComments);
        interViewService.insertComment(newComments);
        return Result.success();
    }

}
